<template>
  <div class="environment-container">
    <div class="environment-content">
      <h3 style="padding-bottom: 15px;">运行环境检测</h3>
      <div>
        <el-collapse v-model="activeNames">
          <!-- PHP版本检测 -->
          <el-collapse-item title="PHP版本" name="php">
            <el-descriptions :column="3" border>
              <el-descriptions-item label="当前版本">
                {{ environmentData?.php_version?.current || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="要求版本">
                {{ environmentData?.php_version?.required || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="environmentData?.php_version?.status ? 'success' : 'danger'">
                  {{ environmentData?.php_version?.status ? '通过' : '未通过' }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>

          <!-- PHP扩展检测 -->
          <el-collapse-item title="PHP扩展" name="extensions">
            <el-table :data="Object.entries(environmentData?.extensions || {}).map(([name, info]) => ({
              name,
              ...info
            }))" border>
              <el-table-column prop="name" label="扩展名称" />
              <el-table-column prop="required" label="是否必需">
                <template #default="{ row }">
                  {{ row.required ? '是' : '否' }}
                </template>
              </el-table-column>
              <el-table-column prop="current" label="是否安装">
                <template #default="{ row }">
                  {{ row.current ? '是' : '否' }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag :type="row.status ? 'success' : 'danger'">
                    {{ row.status ? '通过' : '未通过' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>

          <!-- 目录权限检测 -->
          <el-collapse-item title="目录权限" name="directories">
            <el-table :data="Object.entries(environmentData?.directories || {}).map(([name, info]) => ({
              name,
              ...info
            }))" border>
              <el-table-column prop="name" label="目录/文件" />
              <el-table-column prop="path" label="路径" />
              <el-table-column label="状态" width="200">
                <template #default="{ row }">
                  <el-tag :type="row.status ? 'success' : 'danger'">
                    {{ row.status ? '通过' : '未通过' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <div class="environment-actions">
      <el-button @click="handlePrev">上一步</el-button>
      <el-button type="primary" :disabled="!canProceed" @click="handleNext">下一步</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getInstallEnvironment } from '@/api/install'

const router = useRouter()
const environmentData = ref({})
const activeNames = ref(['php', 'extensions', 'directories'])

const canProceed = computed(() => {
  // 检查所有检测项是否通过
  const phpVersionPass = environmentData.value?.php_version?.status
  const extensionsPass = Object.values(environmentData.value?.extensions || {}).every(ext => !ext.required || ext.status)
  const directoriesPass = Object.values(environmentData.value?.directories || {}).every(dir => dir.status)

  return phpVersionPass && extensionsPass && directoriesPass
})

const handleCheck = async () => {
  try {
    const { data, code } = await getInstallEnvironment()
    if (code === 200) {
      environmentData.value = data
      ElMessage.success('环境检测完成')
    } else {
      ElMessage.error('环境检测失败')
    }
  } catch (error) {
    ElMessage.error('环境检测出错')
    console.error(error)
  }
}

const handlePrev = () => {
  router.back()
}

const handleNext = () => {
  const errors = []
  
  // 检查PHP版本
  if (!environmentData.value?.php_version?.status) {
    errors.push(`PHP版本不满足要求：当前版本 ${environmentData.value?.php_version?.current}，要求版本 ${environmentData.value?.php_version?.required}`)
  }

  // 检查PHP扩展
  const failedExtensions = Object.entries(environmentData.value?.extensions || {})
    .filter(([_, ext]) => ext.required && !ext.status)
    .map(([name]) => name)
  
  if (failedExtensions.length > 0) {
    errors.push(`以下必需的PHP扩展未安装或未启用：${failedExtensions.join('、')}`)
  }

  // 检查目录权限
  const failedDirectories = Object.entries(environmentData.value?.directories || {})
    .filter(([_, dir]) => !dir.status)
    .map(([name]) => name)
  
  if (failedDirectories.length > 0) {
    errors.push(`以下目录或文件权限不正确：${failedDirectories.join('、')}`)
  }

  if (errors.length > 0) {
    ElMessage.error({
      message: errors.join('\n'),
      duration: 5000,
      showClose: true
    })
    return
  }

  router.push('/config')
}

onMounted(() => {
  handleCheck()
})
</script>

<style scoped>
.environment-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.environment-content {
  flex: 1;
  margin-bottom: 20px;
}

.environment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px 0;
}

.check-item {
  margin-bottom: 30px;
}

.check-item h3 {
  margin-bottom: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>